<!--
 * @Date: 2020-07-11 09:33:24
 * @LastEditors: leehave
 * @LastEditTime: 2020-09-14 17:27:21
--> 
<template>
  <div class="charge-prev">
    <div v-if="deviceInfo">
      <van-notice-bar v-if="deviceInfo.device.devicetype !== '2L_Master_Slave'" wrapable :scrollable="false">
        注意事项：<br/>1、扫码前，请按下与插座对应的按钮进行检测；<br/>2、根据语音提示进行下一步操作。
      </van-notice-bar>
      <van-notice-bar v-else wrapable :scrollable="false">
        注意事项：<br/>1、扫码前，请确定充电插头与汽车充电孔连接正常；<br/>2、本充电设备充满自停；充电过程中，如果充电枪脱落，1分钟内自动断电。<br/>3、本充电设备充电结束后，1分钟内结算费用并推送结算信息。<br/>4、充电前请确保个人中心有余额。
      </van-notice-bar>
    </div>
    <div class="normal-padding">
      <div class="address" v-if="deviceInfo">
        <van-icon :name="location" size="24" />
        {{deviceInfo.device.area}}
      </div>
    </div>

    <!-- <van-cell-group>
      <van-cell title="充电插座" :value="port.label" @click="selectPort" is-link />
      <van-cell title="充电时长" :value="time.label" @click="selectTime" is-link v-if="!hasPort" />
    </van-cell-group> -->
    <van-cell title="请选择充电插座" v-if="!hasPort"/>
    <van-cell class="choose-has-choose" title="已选择充电插座" :value="port.label" v-if="hasPort"/>
    <van-cell title="请选择充电时长" v-if="hasPort"/>
    <!-- 按钮组 -->
    <div class="choose-option-v2 not-has-port" v-if="!hasPort">
      <ul class="choose_actionsheet">
        <li 
        class="choose-item" 
        :class="item.active ? 'choose-active' : ''"
        v-for="(item,index) in chargePortList" 
        @click="handleSelectPort(item,index)"
        :key="index">
          <span class="choose-substance">
            {{item.port}}
          </span>
        </li>
      </ul>
    </div>
    <!-- 按钮组 -->

    <!-- 时间组 -->
    <div class="choose-time-v2 has-port" v-if="hasPort">
      <ul class="choose-time_actionsheet">
          <li 
            class="choose-item" 
            :class="[ item.active ? 'choose-active' : '', item.disabled ? 'choose-disabled' : '' ]"
            v-for="(item,index) in chargeTimeList" 
            @click="handleSelectTime(item,index)"
            :key="index">
            {{item.timeName}}
          </li>
        </ul>
    </div>
    <!-- 时间组 -->

    <!-- 时间选择弹出 -->
    <van-popup
      v-model="timePopup"
      closeable
      close-icon="close"
      position="bottom"
      class="time-popup"
      :style="{ height: '50%' }"
    >
    <div class="popup-choose-time">
      <van-cell class="choose-has-choose" title="已选择充电插座:" :value="port.label" />
      <van-cell :border="false" >
        <template #title>
          <h2 class="custom-title">请选择充电时长</h2>
        </template>
        <!-- <div class="choose-right-time">
          <div class="choose-option">
            <span class="tag can">可选</span>
            <span class="tag not">不可选</span>
          </div>
        </div> -->
      </van-cell>
      <div class="choose-time-v2">
        <ul class="choose-time_actionsheet">
          <li 
            class="choose-item" 
            :class="[ item.active ? 'choose-active' : '', item.disabled ? 'choose-disabled' : '' ]"
            v-for="(item,index) in chargeTimeList" 
            @click="handleSelectTime(item,index)"
            :key="index">
            {{item.timeName}}
          </li>
        </ul>
      </div>
    </div>
    </van-popup>
    <!-- 时间选择弹出 -->

    <div class="sure-area">
      <!-- <van-button block color="#409EFF" @click="handleCharge">确定</van-button> -->

      <notice-panel type="warning" title="温馨提示" :desc="noticeText"></notice-panel>
    </div>

    <!-- <van-popup v-model="chargePortPicker" position="bottom">
      <van-picker
        title="充电插座"
        show-toolbar
        :columns="chargePortList"
        @confirm="chargePortConfirm"
        @cancel="chargePortCancel"
        value-key="port"
      />
    </van-popup>

    <van-popup v-model="chargeTimePicker" position="bottom">
      <van-picker
        title="充电时长"
        show-toolbar
        :columns="chargeTimeList"
        @confirm="chargeTimeConfirm"
        @cancel="chargeTimeCancel"
        value-key="timeName"
      />
    </van-popup> -->

  </div>
</template>

<script>
import staticPath from "@/assets/json/index";
import noticePanel from "@/components/notice-panel/index";
import {
  queryDeviceActive,
  openPayment,
  queryByQrCode,
  chargeAdd,
} from "@/service/user";
import { mapGetters } from "vuex";
import { GetQueryString } from "@/utils/index";
import { initWxJSDK } from "@/utils/wx-util";
import { log } from 'util';
export default {
  data() {
    return {
      location: staticPath.location,
      timePopup: false,
      chargeState: 1,
      port: {
        value: "",
        label: "",
      },
      time: {
        value: "",
        label: "",
      },
      chargePortPicker: false,
      chargeTimePicker: false,
      snapDialog: false, //临时支付
      confirmText: "取消",
      cancelText: "确认",
      noticeDialog: false,
      noticeText:
        "临时充电不退费，请您合理使用。建议充值会员，享受先充电后扣费哦！",
      deviceInfo: null,
      hasPort: false, //二路设备自带port
      chargePortList: [], //设备端口信息
      chargeTimeList: [], //充电时长模板
      routerQuery: {}, //路由参数存储
      money: 0, //计算价格
      type: "wallet", //充值类型
      templateName: "", //如果显示智能充电文本才会用到
      walletAccount:
        (this.$store.state.user.userInfo.points * 100 + this.$store.state.user.userInfo.givePoints * 100) / 100,
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    this.fetchInitWxutil();
    let routerQuery = this.$route.query;
    console.log(this.userInfo,'this.userInfo')
    if(this.userInfo && this.userInfo.openId !== undefined){
      let params = {}
      if (Object.keys(routerQuery).length) {
        this.routerQuery = routerQuery;
        if (routerQuery.hasOwnProperty("port") && routerQuery.port !== undefined) {
          this.hasPort = true;
          this.port.value = routerQuery.port;
          this.port.label = routerQuery.port;
          if(routerQuery.hasOwnProperty("deviceId")){
            params.qrNum = routerQuery.deviceId + routerQuery.port
          }else{
            params.qrNum = routerQuery.qrNum + this.port.value
          }
        }else{
          params.qrNum = routerQuery.qrNum + this.port.value
        }
        params.orgId = this.$store.state.user.orgId
        this.queryDeviceInfo(params);
      } else {
        this.$toast("缺少参数");
      }
    }else{
      console.log(this.userInfo,'this.userInfo 2')
      
    }
  },
  mounted() {},
  // watch: {
  //   'userInfo': function(oldv,newv){
  //     console.log(oldv,newv,'userInfo')
  //     let routerQuery = this.$route.query;
  //     let params = {}
  //     if (Object.keys(routerQuery).length) {
  //       this.routerQuery = routerQuery;
  //       if (routerQuery.hasOwnProperty("port") && routerQuery.port !== undefined) {
  //         this.hasPort = true;
  //         this.port.value = routerQuery.port;
  //         this.port.label = routerQuery.port;
  //         if(routerQuery.hasOwnProperty("deviceId")){
  //           params.qrNum = routerQuery.deviceId + routerQuery.port
  //         }else{
  //           params.qrNum = routerQuery.qrNum + this.port.value
  //         }
  //       }else{
  //         params.qrNum = routerQuery.qrNum + this.port.value
  //       }
  //       params.orgId = this.$store.state.user.orgId
  //       this.queryDeviceInfo(params);
  //     } else {
  //       this.$toast("缺少参数");
  //     }
  //   }
  // },
  methods: {
    async fetchInitWxutil(){
      await initWxJSDK(['chooseImage', 'uploadImage', 'previewImage', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareTimeline', 'chooseWXPay', 'scanQRCode']);
    },
    /**
     * 获取设备信息
     */
    async queryDeviceInfo(params) {
      let result = await queryByQrCode(params);
      if (result.respCode !== "000000") {
        this.$toast(result.respMsg);
      } else {
        this.$nextTick(() => {
        
          this.deviceInfo = result.respObject;
          console.log(result.respObject,'deviceInfo',this.deviceInfo,'this deviceInfo')
          // 充电时长条件限制
          let chargeTimeList = this.deviceInfo.templateItems;
          console.log(chargeTimeList,'chargeTimeList')
          if(result.respObject.device.devicetype === 'CAR_EQUIPMENT'){
            this.noticeText = '本汽车充电桩收取费用如下：电费1元/度，服务费0.6元/度。'
            this.hasPort = true;
          }
          if (
            result.respObject.device.devicetype === "2L_Master_Slave" ||
            result.respObject.device.devicetype === "2L_GPRS" ||
            result.respObject.device.devicetype === "CAR_EQUIPMENT"
          ) {
            this.port.value = result.respObject.devicePort[0].port;
            this.port.label = result.respObject.devicePort[0].port;
            this.hasPort = true;
          }
          let con = 1,
            bigKey,
            smallKey,
            bigChargeTime = 0,
            smallChargeTime = 800;
  
          for (let key in chargeTimeList) {
            let act = chargeTimeList[key];
            if (act.chargeTime > bigChargeTime) {
              bigChargeTime = act.chargeTime;
              bigKey = key;
            }
            if (act.chargeTime < smallChargeTime) {
              smallChargeTime = act.chargeTime;
              smallKey = key;
            }
          }
          for (let key in chargeTimeList) {
            chargeTimeList[key].active = false
            let act = chargeTimeList[key];
            let timeName = act.timeName;
            // 会员享受智能充电
            
            if (key == bigKey && chargeTimeList.length != 1) {
              chargeTimeList[key].timeName = "智能充电";
              if(this.walletAccount <= 0){
                chargeTimeList.pop(key)
              }
              console.log(key,bigKey,'key bigKey')
            }
            // 低于设备设置金额禁止点击
            // if (
            //   this.walletAccount < this.deviceInfo.device.autoPrice &&
            //   this.walletAccount > 0 &&
            //   key != smallKey
            // ) {
            //   chargeTimeList[key].disabled = true;
            // }
          }
          let devicePort = result.respObject.devicePort
          devicePort.map(item => {
            item.active = false
          })
          // **** this.$set(this.chargeList,currentPage,result.respObject.list)
          console.log(chargeTimeList,'chargeTimeList 处理后的数据',this.deviceInfo,'deviceInfo')
          this.chargePortList = devicePort;
          this.chargeTimeList = chargeTimeList;
        })
      }
    },
    selectPort() {
      this.chargePortPicker = true;
    },
    selectTime() {
      this.chargeTimePicker = true;
    },
    /**
     * 充电插座确认选择
     */
    chargePortConfirm(value, index) {
      let port = {
        value: value.port,
        label: this.chargePortList[index]["port"],
      };
      this.port = port;
      this.chargePortPicker = false
    },
    chargePortCancel(event) {
      this.chargePortPicker = false;
    },
    chargeTimeConfirm(value, index) {
      console.log(value,index)
      let time = {
        value: value.chargeTime,
        label: this.chargeTimeList[index]["timeName"],
      };
      this.templateName = this.chargeTimeList[index]["timeName"];
      this.time = time;
      this.setMoney(value.chargeTime);
      this.chargeTimePicker = false
    },
    chargeTimeCancel(event) {
      this.chargeTimePicker = false;
    },

    // 非会员价格赋值
    setMoney(time) {
      for (let i = 0; i < this.deviceInfo.templateItems.length; i++) {
        if (this.deviceInfo.templateItems[i].chargeTime == time) {
          this.money = parseFloat(this.deviceInfo.templateItems[i].usePoints); // 非会员价格
          break;
        }
      }
      if (
        null == this.money ||
        this.money === "undefined" ||
        this.money === undefined
      ) {
        this.$toast("单价错误...");
        return;
      }
    },
    /**
     * 充电逻辑
     */
    handleCharge() {
      let device = this.deviceInfo;
      if(this.port.value == ''){
        this.$toast('请选择充电插座')
        return
      }
      if(this.time.value == ''){
        this.$toast('请选择充电时间')
        return 
      }
      if (device.device.free == "1") {
        this.type = "wechat"; // 临时充电
        this.money = 0;
        this.$dialog
          .confirm({
            title: "提示",
            message: "本次充电免费",
            closeOnPopstate: true,
            closeOnClickOverlay: true,
            className: 'choose-dialog',
            overlayClass: 'choose-overLay',
          })
          .then(() => {
            this.invokeServerCharging();
          })
          .catch(() => {});
      } else if (this.deviceInfo.device.onlyVip == "L") {
        this.$dialog
          .confirm({
            title: "提示",
            closeOnPopstate: true,
            closeOnClickOverlay: true,
            className: 'choose-dialog',
            overlayClass: 'choose-overLay',
            message: `插座${this.port.value}号，充电时长:${this.templateName}"。点击确认开始充电。"`,
          })
          .then(() => {
            wxpay(); //只允许单次支付
          });
      } else if (this.deviceInfo.device.onlyVip == "Y" && this.walletAccount <= 0) {
        // 如果类型是Y,只能会员充电
        let msg =
          '亲，您余额不足不能使用，点击"确定"去充值成为会员后使用此功能...';
        this.reCharge(msg);
      } else if (this.deviceInfo.device.onlyVip == "Y" && this.walletAccount > 0) {
        this.type = "wallet"; // 钱包充电
        if (this.templateName == "智能充电") {
          this.templateName = "智能充电，充满自停";
        }
        let msg = `插座:${this.port.value}号，充电时长:${this.templateName}。点击确认开始充电。`;
        if (this.deviceInfo.device.devicetype == "CAR_EQUIPMENT") {
          msg =
            "插座:" +
            this.port.value +
            "号，智能充电，充满自停。点击确认开始充电。";
        }
        this.memCharge(msg);
      } else if (this.walletAccount > 0) {
        this.type = "wallet"; // 钱包充电
        if (this.templateName == "智能充电") {
          this.templateName = "智能充电，充满自停";
        }
        let msg = `插座：${this.port.value}号，充电时长：${this.templateName}。根据功率自动计算费用。`;
        this.memCharge(msg);
      } else if (this.walletAccount <= 0) {
        let msg = `插座：${this.port.value}号，充电时长：${this.templateName}点击"临时支付" 支付完成后开始充电，点击"充值" 支付完成后享受会员价格！`;
        this.chargeOrPay(msg); // 充值钱包或单次支付
      } else {
        this.$toast("充电类型判断错误");
      }
    },
    //调用服务器充电
    async invokeServerCharging() {
      let device = this.deviceInfo;
      let params = {
        specialId: this.$store.state.user.userInfo.specialId,
        openId: this.$store.state.user.userInfo.openId,
        payPoint: this.money,
        port: this.port.value,
        deviceCode: device.device.deviceCode,
        deviceName: device.device.area,
        payType: this.type,
        chargeHour: this.time.value,
        orgId: device.device.orgId,
        deviceType: device.device.devicetype,
      };
      // 充电接口
      let result = await chargeAdd(params);
      if (result.respCode !== "000000") {
        this.$toast(result.respMsg);
      } else {
        this.$router.replace({
          path: "/user/charge/record",
        });
      }
    },
    reCharge(msg) {
      this.$dialog
        .confirm({
          title: "提示",
          message: msg,
          closeOnPopstate: true,
          className: 'choose-dialog',
          overlayClass: 'choose-overLay',
          closeOnClickOverlay: true
        })
        .then(() => {
          // 去充值
          this.$router.push({
            path: `/user/balance?chargeType=wallet&qrNum=${this.deviceInfo.devicePort[0].qrNum}`,
          });
        })
        .catch(() => {});
    },
    memCharge(msg) {
      this.$dialog
        .confirm({
          title: "提示",
          message: msg,
          closeOnPopstate: true,
          closeOnClickOverlay: true,
          className: 'choose-dialog',
          overlayClass: 'choose-overLay',
        })
        .then(() => {
          this.invokeServerCharging();
        })
        .catch(() => {});
    },
    
    chargeOrPay(msg) {
      let that = this
      this.$dialog
        .confirm({
          title: "提示",
          message: msg,
          closeOnPopstate: true,
          closeOnClickOverlay: true,
          confirmButtonText: "充值",
          confirmButtonColor: "#3492ff",
          allowHtml: true,
          cancelButtonText: "临时支付",
          cancelButtonColor: "#333333",
          overlayClass: 'choose-overLay',
          className: 'choose-dialog',
          beforeClose(action, done) {
            if (action === 'confirm') {
              that.$router.push({
                path: `/user/balance?chargeType=wallet&qrNum=${that.deviceInfo.devicePort[0].qrNum}`,
              });
              done();
            } else if(action === 'cancel'){
              that.wxpay();
              done();
              console.log(action,'action')
            }
            else {
              console.log(action,'action')
              done();
            }
          },
        })
    },
    async wxpay() {
      let device = this.deviceInfo;
      let params = {
        specialId: this.$store.state.user.userInfo.specialId,
        openId: this.$store.state.user.userInfo.openId,
        totalFee: this.money,
        port: this.port.value,
        deviceCode: device.device.deviceCode,
        deviceName: device.device.area,
        payType: "wechat",
        chargeHour: this.time.value,
        orgId: device.device.orgId,
        deviceType: device.device.devicetype,
      };
      // 微信支付
      let result = await openPayment(params);
      if (result.respCode !== "000000") {
        this.$toast(result.respMsg);
      } else {
        let data = result.respObject;
        if (typeof WeixinJSBridge == "undefined") {
          if (document.addEventListener) {
            document.addEventListener(
              "WeixinJSBridgeReady",
              this.onBridgeReady(data),
              false
            );
          } else if (document.attachEvent) {
            document.attachEvent(
              "WeixinJSBridgeReady",
              this.onBridgeReady(data)
            );
            document.attachEvent(
              "onWeixinJSBridgeReady",
              this.onBridgeReady(data)
            );
          }
        } else {
          this.onBridgeReady(data);
        }
      }
    },
    onBridgeReady(json) {
      let that = this;
      WeixinJSBridge.invoke("getBrandWCPayRequest", json, function (res) {
        // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回 ok，但并不保证它绝对可靠。
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          that.$router.replace({
            path: "/user/charge/record",
          });
        } else {
          that.$toast("支付失败");
        }
      });
    },
    handleNumConfim() {
      this.noticeDialog = false;
    },
    handleNumCancel() {
      this.noticeDialog = false;
    },
    handleNumClose() {
      this.noticeDialog = false;
    },
    /**点击选择插座v2 */
    handleSelectPort(item,index){
      this.chargePortList.map((item,idx) => {
        idx === index ? (item.active = true) : (item.active = false)
      })
      this.timePopup = true
      this.chargeTimeList.map(item => {
        item.active = false
      })
      this.port.value = item.port
      this.port.label = item.port
      this.time.value = ''
      this.time.label = ''
      console.log(item,'handleSelectPort')
    },
    /**点击选择时间v2 */
    handleSelectTime(item,index){
      console.log(index,'handleSelectTime')
      let chargeTimeList = Object.assign([],this.chargeTimeList)
      chargeTimeList.map((itm,idx) => {
        // if(this.chargeTimeList[index].disabled == true){
        //   return 
        // }
        idx === index ? (itm.active = true) : (itm.active = false)
      })
      this.chargeTimeList = chargeTimeList
      this.timePopup = false
      let time = {
        value: item.chargeTime,
        label: item.timeName
      }
      this.time = time
      this.templateName = item.timeName
      this.setMoney(item.chargeTime)
      this.handleCharge()
      console.log(item,'handleSelectTime');
    }
  },
  components: {
    noticePanel,
  },
};
</script>

<style lang="less">
.charge-prev {
  .address {
    background: #a7d2f9;
    color: #3585dc;
    padding: 8px 20px 8px 5px;
    border-radius: 5px;
    i {
      display: inline-block;
      vertical-align: middle;
    }
  }
}
.sure-area {
  margin-top: 30px;
  padding: 15px;
}
.common-dialog {
  .notice {
    padding: 20px 30px;
    font-size: 14px;
    color: #333;
    line-height: 1.5;
  }
}
</style>
